using System;
using System.Collections;
using System.ComponentModel;
using System.Configuration;
using System.Data;
using System.Drawing;
using System.Web;
using System.Web.SessionState;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.HtmlControls;
using System.Xml;

using LocalBoard.Domain;
using LocalBoard.Controller;

namespace LocalBoard.Web
{
	/// <summary>
	/// Summary description for JoinClub.
	/// </summary>
	public partial class JoinClub : System.Web.UI.Page
	{
	
		protected string xmlForm = "";
		private XmlDocument ClubJoinFormResultXmlDoc;
		private Club _currentClub;
		private string _joinResultFileName = "";

		private AdminController _controller;
		private ClubController _clubController;
		private DataTable _xmlDataTable = null;

		protected void Page_Load(object sender, System.EventArgs e)
		{
			// Put user code to initialize the page here
		}

		protected void Page_Init(object sender, System.EventArgs e)
		{
			_controller = new AdminController(Global.AccessorFactory);
			_currentClub = _controller.GetClub(Int32.Parse(this.CurrentClubId));

			if(_currentClub != null)
			{
				_clubController = new ClubController(_currentClub.Id, Global.AccessorFactory);

				if(Request.IsAuthenticated && IsUserAlreadyClubMember(_currentClub.Id, Security.CurrentUser.Id))
				{
					//Redirect to club main page..
					//Response.Redirect("");
				}
				else
				{

					try
					{
						_joinResultFileName = _currentClub.UniqueName.Trim() + Global.JOIN_FORM_RESULT;
						ClubJoinFormResultXmlDoc = new XmlDocument();
						ClubJoinFormResultXmlDoc.Load(Server.MapPath("Results/" + _joinResultFileName));
						//Create JoinFormSrc method in Club.cs
//						xmlForm = _currentClub.JoinFormSrc;
						if(xmlForm == "")
							xmlForm = ConfigurationSettings.AppSettings["defaultForm"];

						DataSet XmlDataSet = new DataSet();
						XmlDataSet.ReadXml(HttpContext.Current.Server.MapPath("Forms/" + xmlForm),
							XmlReadMode.InferSchema);

						_xmlDataTable = new DataTable();
						_xmlDataTable = XmlDataSet.Tables["Fields"];
						loadForm();
						joinClubButton.Visible = true;
					}
					catch
					{
						formHolder.Controls.Add(new LiteralControl("No club-join form found."));
					}

				}
			}
		}

		private void loadForm()
		{
			formHolder.Controls.Add(new LiteralControl("<table><tr>"));
			//subject control
			TextBox subjectBox = new TextBox();
			subjectBox.ID = "subject";
			RequiredFieldValidator subjValidator = new RequiredFieldValidator();
			subjValidator.ErrorMessage = "Required field is missing.";
			subjValidator.ControlToValidate = "subject";

			formHolder.Controls.Add(new LiteralControl("<td>Subject</td>"));
			formHolder.Controls.Add(new LiteralControl("<td>"));
			formHolder.Controls.Add(subjectBox);
			formHolder.Controls.Add(subjValidator);
			formHolder.Controls.Add(new LiteralControl("</td>"));
			formHolder.Controls.Add(new LiteralControl("<tr>"));

			for(int i = 0;i < _xmlDataTable.Rows.Count;i++)
			{
				string objId = "controlId" + i.ToString();
				string objLabel = _xmlDataTable.Rows[i]["Label"].ToString();
				bool required = _xmlDataTable.Rows[i]["Required"].ToString().ToUpper() == "YES";
				if(_xmlDataTable.Rows[i]["Control"].ToString() == "CheckBox")
				{
					CheckBox cBox = new CheckBox();
					cBox.ID = objId;
					cBox.Text = objLabel;
					cBox.TextAlign = TextAlign.Left;
					formHolder.Controls.Add(new LiteralControl("<td colspan='2'>"));
					formHolder.Controls.Add(cBox);
					formHolder.Controls.Add(new LiteralControl("</td>"));
				}
				else if(_xmlDataTable.Rows[i]["Control"].ToString() == "TextBox")
				{
					Label label = new Label();
					label.Text = objLabel;
					TextBox tBox = new TextBox();
					tBox.ID = objId;
					RequiredFieldValidator validator = null;
					if(required)
					{
						validator = new RequiredFieldValidator();
						validator.ErrorMessage = "Required field is missing.";
						validator.ControlToValidate = objId;
					}
					formHolder.Controls.Add(new LiteralControl("<td>"));
					formHolder.Controls.Add(label);
					formHolder.Controls.Add(new LiteralControl("</td>"));
					formHolder.Controls.Add(new LiteralControl("<td>"));
					formHolder.Controls.Add(tBox);
					if(validator != null)
						formHolder.Controls.Add(validator);
					formHolder.Controls.Add(new LiteralControl("</td>"));
				}
				else if(_xmlDataTable.Rows[i]["Control"].ToString() == "CheckBoxList")
				{
					Label label = new Label();
					label.Text = objLabel;
					CheckBoxList cbList = new CheckBoxList();
					cbList.ID = objId;
					string[] cbItems = _xmlDataTable.Rows[i]["Text"].ToString().Split(',');
					for (int j=0; j < cbItems.Length; j++)
					{
						ListItem item = new ListItem(cbItems[j], j.ToString());
						cbList.Items.Add(item);
					}
					formHolder.Controls.Add(new LiteralControl("<td>"));
					formHolder.Controls.Add(label);
					formHolder.Controls.Add(new LiteralControl("</td>"));
					formHolder.Controls.Add(new LiteralControl("<td>"));
					formHolder.Controls.Add(cbList);
					formHolder.Controls.Add(new LiteralControl("</td>"));
				}
				else if(_xmlDataTable.Rows[i]["Control"].ToString() == "DropDownList")
				{
					Label label = new Label();
					label.Text = objLabel;
					DropDownList ddList = new DropDownList();
					ddList.ID = objId;
					string[] ddItems = _xmlDataTable.Rows[i]["Text"].ToString().Split(',');
					for (int j=0; j < ddItems.Length; j++)
					{
						ListItem item = new ListItem(ddItems[j], j.ToString());
						ddList.Items.Add(item);
					}
					formHolder.Controls.Add(new LiteralControl("<td>"));
					formHolder.Controls.Add(label);
					formHolder.Controls.Add(new LiteralControl("</td>"));
					formHolder.Controls.Add(new LiteralControl("<td>"));
					formHolder.Controls.Add(ddList);
					formHolder.Controls.Add(new LiteralControl("</td>"));
				}
				else if(_xmlDataTable.Rows[i]["Control"].ToString() == "Label")
				{
					Label label = new Label();
					label.Text = objLabel;
					label.ID = objId;
					formHolder.Controls.Add(new LiteralControl("<td colspan='2'>"));
					formHolder.Controls.Add(label);
					formHolder.Controls.Add(new LiteralControl("</td>"));
				}
				else if(_xmlDataTable.Rows[i]["Control"].ToString() == "ListBox")
				{
					Label label = new Label();
					label.Text = objLabel;
					ListBox lBox = new ListBox();
					lBox.ID = objId;
					string[] lBoxItems = _xmlDataTable.Rows[i]["Text"].ToString().Split(',');
					for (int j=0; j < lBoxItems.Length; j++)
					{
						ListItem item = new ListItem(lBoxItems[j], j.ToString());
						lBox.Items.Add(item);
					}
					formHolder.Controls.Add(new LiteralControl("<td>"));
					formHolder.Controls.Add(label);
					formHolder.Controls.Add(new LiteralControl("</td>"));
					formHolder.Controls.Add(new LiteralControl("<td>"));
					formHolder.Controls.Add(lBox);
					formHolder.Controls.Add(new LiteralControl("</td>"));
				}
				else if(_xmlDataTable.Rows[i]["Control"].ToString() == "Multiline")
				{
					Label label = new Label();
					label.Text = objLabel;
					TextBox tBox = new TextBox();
					tBox.TextMode = TextBoxMode.MultiLine;
					tBox.Width = Unit.Pixel(200);
					tBox.Rows = 10;
					tBox.ID = objId;
					formHolder.Controls.Add(new LiteralControl("<td>"));
					formHolder.Controls.Add(label);
					formHolder.Controls.Add(new LiteralControl("</td>"));
					formHolder.Controls.Add(new LiteralControl("<td>"));
					formHolder.Controls.Add(tBox);
					formHolder.Controls.Add(new LiteralControl("</td>"));
				}
				else if(_xmlDataTable.Rows[i]["Control"].ToString() == "RadioButtonList")
				{
					Label label = new Label();
					label.Text = objLabel;
					RadioButtonList rbList = new RadioButtonList();
					rbList.ID = objId;
					string[] lbListItems = _xmlDataTable.Rows[i]["Text"].ToString().Split(',');
					for (int j=0; j < lbListItems.Length; j++)
					{
						ListItem item = new ListItem(lbListItems[j], j.ToString());
						rbList.Items.Add(item);
					}
					rbList.TextAlign = TextAlign.Right;
					rbList.RepeatDirection = RepeatDirection.Vertical;
					formHolder.Controls.Add(new LiteralControl("<td>"));
					formHolder.Controls.Add(label);
					formHolder.Controls.Add(new LiteralControl("</td>"));
					formHolder.Controls.Add(new LiteralControl("<td>"));
					formHolder.Controls.Add(rbList);
					formHolder.Controls.Add(new LiteralControl("</td>"));
				}
				formHolder.Controls.Add(new LiteralControl("</tr>"));
			}
			formHolder.Controls.Add(new LiteralControl("</table>"));
		}

		public bool DidUserAlreadyWriteSelfIntro(int userProfileId)
		{
			XmlNode resultNode = ClubJoinFormResultXmlDoc.SelectSingleNode("//NewDataSet/Result[@ProfileId="+userProfileId.ToString()+"]");
			return resultNode != null;
		}

		private bool IsUserAlreadyClubMember(int clubId, int profileId)
		{
			return _clubController.IsUserInTheClub(profileId);
		}

		#region Web Form Designer generated code
		override protected void OnInit(EventArgs e)
		{
			//
			// CODEGEN: This call is required by the ASP.NET Web Form Designer.
			//
			InitializeComponent();
			base.OnInit(e);
		}
		
		/// <summary>
		/// Required method for Designer support - do not modify
		/// the contents of this method with the code editor.
		/// </summary>
		private void InitializeComponent()
		{    

		}
		#endregion

		protected void joinClubButton_Click(object sender, System.EventArgs e)
		{
			if(Request.IsAuthenticated && !DidUserAlreadyWriteSelfIntro(Security.CurrentUser.Id))
			{
				try
				{
					createResultXml();
				}
				catch(Exception ex)
				{
					errorMsg.Text += "\nThe results could not be saved." + "\n"+ex.Message;
					errorMsg.Visible = true;
				}
			}
			else
			{
				if(!Request.IsAuthenticated)
					errorMsg.Text = "Please log-in first to join this club.";
				else
					errorMsg.Text = "You are alredy a member of this club.";
				errorMsg.Visible = true;
			}
		}

		private void createResultXml()
		{
			XmlNode newResultNode = CreateNewNode();
			ClubJoinFormResultXmlDoc.DocumentElement.AppendChild(newResultNode);
			ClubJoinFormResultXmlDoc.Save(Server.MapPath("Results/" + _joinResultFileName));

			//Save user join result into Message.xml:boardId=1 to display in message view list and message view
			//CreateMessage("Test Subject", _joinResultFileName);
			//Add user into Club_UserProfile.xml file
//			AddNewUser();
		}

		public XmlNode CreateNewNode()
		{
			XmlNode newResultNode = ClubJoinFormResultXmlDoc.CreateElement("Result");
			newResultNode.Attributes.Append(ClubJoinFormResultXmlDoc.CreateAttribute("ProfileId"));
//			newResultNode.Attributes["ProfileId"].InnerText = UserProfileManager.CurrentUser.Id.ToString();
			
			XmlNode formSubjectNode = ClubJoinFormResultXmlDoc.CreateElement("Subject");
			object subject = FindControl("subject");
			formSubjectNode.InnerText = ((TextBox) subject).Text;
			newResultNode.AppendChild(formSubjectNode);

			XmlNode formNode = ClubJoinFormResultXmlDoc.CreateElement("Form");
			formNode.InnerText = xmlForm;
			newResultNode.AppendChild(formNode);

			for(int i = 0;i < _xmlDataTable.Rows.Count;i++)
			{
				XmlNode newNode = ClubJoinFormResultXmlDoc.CreateElement("Question");
				newNode.Attributes.Append(ClubJoinFormResultXmlDoc.CreateAttribute("Title"));
				newNode.Attributes["Title"].InnerText = _xmlDataTable.Rows[i]["Label"].ToString();

				string controlId = "controlId" + i.ToString();
				object c = FindControl(controlId);
				string answer = "";
				if(_xmlDataTable.Rows[i]["Control"].ToString() == "CheckBox")
				{
					answer = ((CheckBox)c).Checked.ToString();
				}
				else if(_xmlDataTable.Rows[i]["Control"].ToString() == "CheckBoxList")
				{
					CheckBoxList cbl = (CheckBoxList)c;
					string s = "";
					for (int j=0; j < cbl.Items.Count; j++)
					{
						if (cbl.Items[j].Selected )
						{
							s = s + cbl.Items[j].Text;
							s = s + ",";
						}
					}
					if(s != String.Empty)
					{
						s = s.Substring(0,s.Length-1);
					}
					answer = s;
				}
				else if(_xmlDataTable.Rows[i]["Control"].ToString() == "DropDownList")
				{
					answer = ((DropDownList)c).SelectedItem.Text;
				}
				else if(_xmlDataTable.Rows[i]["Control"].ToString() == "Hidden")
				{
					answer = ((TextBox)c).Text;
				}
				else if(_xmlDataTable.Rows[i]["Control"].ToString() == "Label")
				{
					answer = ((Label)c).Text;
				}
				else if(_xmlDataTable.Rows[i]["Control"].ToString() == "ListBox")
				{
					answer = ((ListBox)c).SelectedItem.Text;
				}
				else if(_xmlDataTable.Rows[i]["Control"].ToString() == "Multiline")
				{
					answer = ((TextBox)c).Text;
				}
				else if(_xmlDataTable.Rows[i]["Control"].ToString() == "Password")
				{
					answer = ((TextBox)c).Text;
				}
				else if(_xmlDataTable.Rows[i]["Control"].ToString() == "RadioButtonList")
				{
					answer = ((RadioButtonList)c).SelectedItem.Text;
				}
				else if(_xmlDataTable.Rows[i]["Control"].ToString() == "TextBox")
				{
					answer = ((TextBox)c).Text;
				}
				newNode.InnerText = answer.Trim();
				newResultNode.AppendChild(newNode);
			}
			return newResultNode;
		}

		public string CurrentClubId
		{
			get
			{
				return HttpContext.Current.Request.Params["ClubId"].ToString();
			}
		}

		private void CreateMessage(string subject, string joinFormResultFileName)
		{
			XmlNode node = ClubJoinFormResultXmlDoc.SelectSingleNode("//NewDataSet/Result[@ProfileId="+Security.CurrentUser.Id.ToString()+"]");
			XmlNodeList nodeList = node.ChildNodes;
			string msgBody = "";
			foreach(XmlNode resultNode in nodeList)
			{
				if(resultNode.Name == "Subject" || resultNode.Name == "Form")
					continue;
				if(msgBody != "")
					msgBody += "\r\n" + resultNode.Attributes["Title"].InnerText + ": " + resultNode.InnerText;
				else
					msgBody += resultNode.Attributes["Title"].InnerText + ": " + resultNode.InnerText;
			}
			//load clubBoardController, and post message
		}
	}
}
